<?php
namespace app\index\controller;

use app\index\model\Jssdk;
use app\common\validate\ApplyValidate;
use app\common\model\Apply as ApplyModel;
use app\common\model\Record;
use app\common\model\RecordBrokerage;
use app\common\model\ShareVoucher;
use app\common\model\User;
use app\common\model\UserAccount;
use app\common\model\HtmlToImg;
use app\common\model\Note;

class Apply extends Base
{
    public function index()
    {
        $jssdk = new Jssdk();
        $this->assign('signPackage', $jssdk->GetSignPackage());
        return $this->fetch();
    }

    public function add()
    {
        if(strtotime($this->activity->end_time) < time()) return $this->jsonFail('活动已经结束');
        $data = $this->request->post();
        $applyValidate = new ApplyValidate();
        if(ApplyModel::where(['user_id' => $this->user->id, 'aid' => $this->activity->id])->count() == 1)
            return $this->jsonFail('亲，您已经报过名');
        if($applyValidate->scene('add')->check($data)){
            $applyModel = new ApplyModel();
            $data['user_id'] = $this->user->id;
            $data['aid'] = $this->activity->id;
            $data['number'] = ApplyModel::where(['aid' => $this->activity->id, 'status' => 1])->count() + 1;
            if($applyId = $applyModel->add($data)){
                Note::applySuccess($applyId);
                return $this->jsonSuccess('报名成功', ['baby_name' => $data['baby_name'], 'avatar' => $this->user->avatar, 'rank' => $data['number']]);
            }
            $errMsg = '报名失败';
        }else{
            $errMsg = $applyValidate->getError();
        }
        return $this->jsonFail($errMsg);
    }

    // 投票
    public function vote()
    {
        if(strtotime($this->activity->end_time) < time()) return $this->jsonFail('活动已经结束');
        $applyId = $this->request->param('apply_id');
        $apply = ApplyModel::get($applyId);

        // 判断是否为本人投票
        if($apply->user_id == $this->user->id) return $this->jsonFail('本人不可投票');

        $data = [
            'user_id' => $this->user->id,
            'date' => date('Ymd', time()),
        ];
        if(($this->activity->max_poll > 0) && (Record::where($data)->count() > $this->activity->max_poll))
            return $this->jsonFail('亲, 单日投票已达上限');
        $data['apply_id'] = $applyId;
        if(($this->activity->baby_max_poll > 0) && (Record::where($data)->count() > $this->activity->baby_max_poll))
            return $this->jsonFail('亲, 今日针对该角色的投票已达上限');
        if((new Record())->add($data)) {
            $apply->setInc('poll');

            $applyUser = User::get($apply->user_id);    // 参与者
            $applyAccount = $applyUser->account;        // 参与者账户
            $brokerage = $apply->brokerage;             // 佣金设置
            if(!$brokerage) return $this->jsonSuccess('投票成功');
            // 判断余额是否充足
            if($applyAccount->balance < $brokerage->min_money) return $this->jsonSuccess('投票成功', ['code' => 2, 'msg' => '余额不足']);

            // 判断之前是否投过票或分享过
            $recordBrokerage = RecordBrokerage::get(['user_id' => $this->user->id, 'apply_id' => $applyId]);
            // 判断是否领取过红包
            if($recordBrokerage) {
                if(strtotime($recordBrokerage['vote_time']) != 0) return $this->jsonSuccess('投票成功', ['code' => 3, 'msg' => '已领取过该红包']);
                try{
                    if($recordBrokerage->vote_amount > $applyAccount->balance)
                        $recordBrokerage->vote_amount = $applyAccount->balance;
                    (new UserAccount())->activityEdit($recordBrokerage->vote_amount, $this->user->account, $applyAccount);
                    $recordBrokerage->vote_time = time();
                    $recordBrokerage->save();
                    $resultJpg = HtmlToImg::jpg($this->user->id, $apply->id);
                    return $this->jsonSuccess('投票成功', ['code' => 4,
                        'jpg' => $resultJpg,
                        'apply' => $apply,
                    ]);
                } catch (\Exception $e) {
                    return $this->jsonFail($e->getMessage());
                }
            }

            // 之前未点赞也未分享
            try{
                $maxMoney = min($applyAccount->balance, $brokerage->max_money);
                $brokerageAmount = mt_rand($brokerage->min_money * 100, $maxMoney * 100) / 100;
                $data = ['user_id' => $this->user->id, 'apply_id' => $applyId];
                $result = (new RecordBrokerage())->allot($brokerage, $brokerageAmount, $data);
                (new UserAccount())->activityEdit($result['vote_amount'], $this->user->account, $applyAccount);
                $resultJpg = HtmlToImg::jpg($this->user->id, $apply->id);
                return $this->jsonSuccess('投票成功', ['code' => 4,
                    'jpg' => $resultJpg,
                    'apply' => $apply,
                ]);
            } catch (\Exception $e) {
                return $this->jsonFail($e->getMessage());
            }
            return $this->jsonSuccess('投票成功');
        } else {
            return $this->jsonFail('投票失败');
        }
    }

    public function htmlToJpg()
    {
        return $this->fetch();
    }
}
